package com.dts.backproject.controller;

import com.dts.backproject.entity.po.Result;
import com.dts.backproject.entity.po.Video;
import com.dts.backproject.service.UserInfoService;
import com.dts.backproject.service.VideoService;
import com.dts.backproject.util.COSUploader;
import com.dts.backproject.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
public class FileUploadController {

    @Autowired
    private COSUploader cosUploader;
    
    @Autowired
    private UserInfoService userInfoService;
    
    @Autowired
    private VideoService videoService;

    /**
     * 上传头像文件
     * @param file 头像文件
     * @param email 用户邮箱
     * @return 上传结果
     */
    @PostMapping("/avatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file, 
                              @RequestParam("email") String email) {
        try {
            // 验证文件（限制为5MB）
            String validationError = FileUploadUtil.validateImageFile(file, 5 * 1024 * 1024);
            if (validationError != null) {
                return Result.error(validationError);
            }
            
            // 上传文件到COS
            String avatarUrl = cosUploader.uploadFile(file, "avatars");
            
            // 更新用户头像URL到数据库
            userInfoService.updateAvatarUrl(email, avatarUrl);
            
            Map<String, String> result = new HashMap<>();
            result.put("url", avatarUrl);
            result.put("message", "头像上传成功");
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传通用文件
     * @param file 文件
     * @param folder 存储文件夹
     * @return 上传结果
     */
    @PostMapping("/file")
    public Result uploadFile(@RequestParam("file") MultipartFile file,
                           @RequestParam(value = "folder", defaultValue = "files") String folder) {
        try {
            // 验证文件（限制为10MB）
            String validationError = FileUploadUtil.validateFile(file, 10 * 1024 * 1024);
            if (validationError != null) {
                return Result.error(validationError);
            }
            
            // 上传文件到COS
            String fileUrl = cosUploader.uploadFile(file, folder);
            
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("message", "文件上传成功");
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result test() {
        return Result.success("后端服务正常运行");
    }

    /**
     * 上传视频文件
     * @param file 视频文件
     * @param title 视频标题
     * @param description 视频描述
     * @param uploaderEmail 上传者邮箱
     * @return 上传结果
     */
    @PostMapping("/video")
    public Result uploadVideo(@RequestParam("file") MultipartFile file,
                             @RequestParam("title") String title,
                             @RequestParam(value = "description", required = false) String description,
                             @RequestParam("uploaderEmail") String uploaderEmail) {
        try {
            // 验证文件（限制为100MB）
            String validationError = FileUploadUtil.validateVideoFile(file, 100L * 1024 * 1024);
            if (validationError != null) {
                return Result.error(validationError);
            }
            
            // 上传视频文件到COS
            String videoUrl = cosUploader.uploadFile(file, "videos");
            
            // 创建视频记录
            Video video = new Video();
            video.setId(UUID.randomUUID().toString());
            video.setTitle(title);
            video.setDescription(description);
            video.setVideoUrl(videoUrl);
            video.setFileSize(file.getSize());
            video.setFileType(file.getContentType());
            video.setUploaderEmail(uploaderEmail);
            video.setStatus("active");
            video.setCreateAt(LocalDateTime.now());
            video.setUpdateAt(LocalDateTime.now());
            
            // 保存到数据库
            videoService.addVideo(video);
            
            Map<String, Object> result = new HashMap<>();
            result.put("videoId", video.getId());
            result.put("videoUrl", videoUrl);
            result.put("title", title);
            result.put("message", "视频上传成功");
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("视频上传失败: " + e.getMessage());
        }
    }
}
